package com.atguigu.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class ZKDemo {

    private ZooKeeper zk;

    /**
     * 1.获得连接对象
     * 2.进行操作
     * 3.关闭资源
     */

    @Before
    public void before() throws IOException {
        //获得连接对象
//        // ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)
//        @param connectString "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"
        String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
        int sessionTimeout=4000;
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            public void process(WatchedEvent event) {

            }
        });
    }
    @Test
    public void test() throws KeeperException, InterruptedException {
        /**
         * create(final String path, byte data[], List<ACL> acl,
         *             CreateMode createMode)
         */
        String s = zk.create("/sanguo ", "xixixi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        System.out.println(s);
    }

    @Test
    public void test2() throws Exception {
        /**
         * 获取子节点并监听
         */
        register();
        Thread.sleep(Long.MAX_VALUE);
    }
    public void register() throws Exception {
        List<String> children = zk.getChildren("/xiyouji", new Watcher() {
            public void process(WatchedEvent event) {
                //处理节点改变后的业务逻辑
                System.out.println("节点改变了");
                //重新注册
                try {
                    register();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        for (String child : children) {
            System.out.println(child);
        }
    }

    @After
    public void after(){
        try {
            if (zk!=null) {
                zk.close();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断子节点是否存在
     */
    @Test
    public void test3() throws KeeperException, InterruptedException {
        Stat exists = zk.exists("/xiyoui", false);
        System.out.println(exists!=null?"存在":"不存在");
    }


}
